package com.zlq.javaWeb3.controller;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * The type File in servlet.
 */
@WebServlet(urlPatterns = "/fileInServlet")
public class FileInServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = Integer.parseInt(req.getParameter("id"));
        String name = null;
        switch (id) {
            case 1:
                name = "D:\\tup\\85791.jpg";
            case 2:
                name = "D:\\tup\\191107.jpg";
        }
        String contentDispostion = "attachment;filename=" + URLEncoder.encode(name, "UTF-8");
        resp.setHeader("content-disposition", contentDispostion);
        resp.setContentType("application/octet-stream");
        FileInputStream in = new FileInputStream(name);
        ServletOutputStream out = resp.getOutputStream();
        byte[] b = new byte[1024];
        int length = 0;
        while ((length = in.read(b)) != -1) {
            out.write(b, 0, length);
        }
        in.close();
        out.close();

    }
}
